#coding=utf-8
__author__ = 'huangzhi'

import simplejson
import jinja2
# import werkzeug.utilsfrom openerp import http
from openerp.http import request

from openerp.addons.web import http
# from opernerp.http import Response
# from openerp.addons.web.http import request
# from openerp.addons.eroad_mweb.controllers import mweb_public
from openerp import SUPERUSER_ID
import datetime
import operator
import urllib
# from eroad_odoo_utils import eroad_utils
# from openerp.addons import eroad_qywechat_api
# from openerp.addons import eroad_gzwechat_api
# from eroad_odoo_utils.eroad_wechat_util import qywechat_sdk, gzwechat_sdk,jssdk_sign
# from eroad_bracelet_web import _get_wx_sdk_jsapi_conf as _get_wx_sdk_jsapi_conf
from eroad_odoo_utils.pinyin import HanYuPinYin
# from openerp.addons.eroad_qywechat_api import conf
import codecs

import itertools

import logging

_logger = logging.getLogger(__name__)


loader = jinja2.PackageLoader('openerp.addons.eroad_bracelet_web_json', 'html')
env = jinja2.Environment(loader=loader, autoescape=True)
env.filters["json"] = simplejson.dumps

class doctor_patient_group_list_json(http.Controller):
    #所有患者的列表
    @http.route('/doctor/all/patient/list', type='http', auth="user", cors='*')
    def doctor_patient_list(self, req, **kw):
        method = req.httprequest.method
        if True:
            pn = req.params.get('pn')
            if (pn==''): pn = 0
            if (pn is None): pn=0
            pn = int(pn)
            if pn<=0: pn = 1

            ps = req.params.get('ps')
            if (ps==''): ps = 0
            if (ps is None): ps = 0
            ps = int(ps)
            if ps <=0: ps = 10

            did = req.params.get('did')
            if (did is None): did = -1
            v = int(did)

            gid = req.params.get('gid')
            if (gid is None): gid = -1
            gid = int(gid)

            pc = 0

            registry = req.registry

            #分页 begin
            sql = """
                    select count(1)
                    from eroad_bracelet_patient a
                    left join eroad_bracelet_doctor_patient_rel d on a.id=d.patient_id
                    left join eroad_bracelet_doctor e on e.id=d.doctor_id
                    left join res_partner f on a.partner_id=f.id
                    left join res_partner g on e.partner_id=g.id
                    left join res_country_state h on f.state_id=h.id
                    where d.doctor_id=%s
                  """ % (did)
            with registry.cursor() as cr:
                cr.execute(sql)
                pc = cr.dictfetchall()[0]["count"]

            if pc < pn *ps:
                pn = int(pc / ps) + 1

                # pc = len(doc_pat_rel_ids)
            # sql = ("select a.patient_id,b.* from eroad_bracelet_doctor_patient_rel a left join eroad_bracelet_patient b on a.patient_id=b.id where a.doctor_id=%s order by a.patient_id limit %s OFFSET %s"  % (docid, ps,(pn-1)*ps))
            sql1 = """
                    select d.doctor_id,d.patient_id, g.name as dname,f.name as pname,coalesce(h.name,'') as state_name,f.city from eroad_bracelet_patient a
                    left join eroad_bracelet_doctor_patient_rel d on a.id=d.patient_id
                    left join eroad_bracelet_doctor e on e.id=d.doctor_id
                    left join res_partner f on a.partner_id=f.id
                    left join res_partner g on e.partner_id=g.id
                    left join res_country_state h on f.state_id=h.id
                    where d.doctor_id=%s %(docid) order by d.patient_id
                    """ % (did)

            if pn<=1:
                sql = sql1 + sql
            # print sql
            with registry.cursor() as cr:
                cr.execute(sql)
                doc_patient_lists = cr.dictfetchall()
            # print pc, pn, ps, doc_patient_lists
            _logger.info( 'sql:%s' % sql)
            patientjson = ''
            for patient in doc_patient_lists:
                _logger.info( 'doctor_id:%s' % patient['did'])
                # print patient["id"], patient["nickname"]
                name = patient['name'] if patient['name'] else patient['nickname']   #修改患者的名称  mazh
                temp = "{'id':'%s','did':'%s','name':'%s','headimgurl':'%s', 'country':'%s','state':'%s','city':'%s','isbind':'%s'}" \
                       % (patient['patient_id'], patient['did'], name, patient['headimgurl'], patient['country_name'],
                          patient['state_name'], patient['city'], patient['isbind'])
                # print temp
                if patientjson!='':
                    patientjson = patientjson + ',' + temp
                else:
                    patientjson = temp

            success = 'true'
            html = ''
            # html = "{'success':'%s','totalcount':'%s','pn':'%s','ps':'%s','title': '我的患者','header':'患者列表'," \
            #        "'docid':'%s','data':[%s]}" % (success, pc, pn, ps, docid, patientjson)

            return request.make_response(html,{
                    'Cache-Control': 'no-cache',
                    'Content-Type': 'text/html; charset=utf-8',
                    'Access-Control-Allow-Origin': '*',
                    'Origin': '*',
                    'Access-Control-Allow-Methods': 'GET,POST',
                    'Access-Control-Allow-Headers': 'Referer, Accept, Origin, User-Agent'
                        })
        else:
            return "{%s}" % (method)


    #2患者分组 http://localhost:48269/doctor/patient/groups/list?did=31
    @http.route('/doctor/patient/groups/list', type='http', auth="user", cors='*')
    def doctor_patient_group_list(self, req, **kw):
        method = req.httprequest.method
        if True:

            did = req.params.get('did')
            if (did is None): did = -1
            did = int(did)

            pc = 0

            registry = req.registry

            #某医生的患者总数
            sql = """
                    select count(*) as dpc from eroad_bracelet_doctor_patient_rel where doctor_id=%s
                  """ % (did)
            with registry.cursor() as cr:
                cr.execute(sql)
                dpc = cr.dictfetchall()[0]["dpc"]
            #分组总的患者数
            sql = """
                    select sum(pc) as ppc from (select distinct doctor_id,patient_id, case when patient_id is null then 0 else 1 end as pc from patient_group  where doctor_id=%s) t
                  """ % (did)
            with registry.cursor() as cr:
                cr.execute(sql)
                ppc = cr.dictfetchall()[0]["ppc"]

            #分页 begin
            sql = """
                    select count(*) from (select id from patient_group where doctor_id=%s group by id,name order by id) t
                  """ % (did)
            with registry.cursor() as cr:
                cr.execute(sql)
                pc = cr.dictfetchall()[0]["count"]

            sql = """
                    select id,name, doctor_id,sum(pc) as pc from patient_group where doctor_id=%s group by id,name,doctor_id order by id
                    """ % (did)
            with registry.cursor() as cr:
                cr.execute(sql)
                doc_patient_groups = cr.dictfetchall()

            templist = []
            temp = {
                'gid':-1,
                'name':'全部',
                'did':did,
                'pc':dpc
            }
            templist.append(temp)
            if doc_patient_groups.__len__()>0:
                temp = {
                    'gid':0,
                    'name':'未分组',
                    'did':did,
                    'pc':dpc-ppc
                }
                templist.append(temp)
            for group in doc_patient_groups:
                temp = {
                    'gid':group['id'],
                    'name':group['name'],
                    'did':did,
                    'pc':group['pc'],

                }
                templist.append(temp)



            success = True

            html = {
                    "success":success,
                    "title": "患者分组",
                    "header":"患者分组",
                    "pc":pc,
                    "data":templist
                    }
            #return html
            html = simplejson.dumps(html)

            return request.make_response(html,{
                    'Cache-Control': 'no-cache',
                    'Content-Type': 'text/html; charset=utf-8',
                    'Access-Control-Allow-Origin': '*',
                    'Origin': '*',
                    'Access-Control-Allow-Methods': 'GET,POST',
                    'Access-Control-Allow-Headers': 'Referer, Accept, Origin, User-Agent'
                        })
        else:
            return "{%s}" % (method)



    #根据医生编号和患者编号取备注未读数
    def doctor_get_unread(self, req, did, pid):
        #患者信息未读条数
        try:
            doctor_id = int(did)
            patient_id = int(pid)

            weekly_line_obj = req.registry['weekly.report.comment.line']
            weekly_comment_obj = req.registry['weekly.report.comment']
            psqi_line_obj = req.registry['psqi.report.comment.line']
            psqi_comment_obj = req.registry['psqi.report.comment']
            weekly_line_unread = len(weekly_line_obj.search(req.cr,SUPERUSER_ID,
                                                            [
                                                                ('is_read','=',False),
                                                                ('line_type','=','patient'),
                                                                ('doctor_id','=',doctor_id),
                                                                ('patient_id','=',patient_id)
                                                            ]))
            weekly_comment_unread = len(weekly_comment_obj.search(req.cr,SUPERUSER_ID,
                                                                  [
                                                                      ('is_read','=',False),
                                                                      ('sponsor','=',2),
                                                                      ('doctor_id','=',doctor_id),
                                                                      ('patient_id','=',patient_id)
                                                                  ]))
            psqi_comment_unread = len(psqi_comment_obj.search(req.cr,SUPERUSER_ID,
                                                              [
                                                                  ('is_read','=',False),
                                                                  ('sponsor','=',2),
                                                                  ('doctor_id','=',doctor_id),
                                                                  ('patient_id','=',patient_id)
                                                              ]))
            psqi_line_unread = len(psqi_line_obj.search(req.cr,SUPERUSER_ID,
                                                        [
                                                            ('is_read','=',False),
                                                            ('line_type','=','patient'),
                                                            ('doctor_id','=',doctor_id),
                                                            ('patient_id','=',patient_id)
                                                        ]))
            unreads = weekly_comment_unread + weekly_line_unread + psqi_line_unread + psqi_comment_unread
            return unreads
        except Exception,e:
            return 0

    #3某医生的某个分组的患者列表
    #(全部)   http://localhost:48269/isleep/doctor/patient/agroups/list?did=31&gid=-1
    #(未分组) http://localhost:48269/isleep/doctor/patient/agroups/list?did=31&gid=0
    #(某分组) http://localhost:48269/isleep/doctor/patient/agroups/list?did=31&gid=5
    @http.route('/doctor/patient/agroups/list', type='http', auth="user", cors='*')
    def doctor_patient_agroups_list(self, req, **kw):
        method = req.httprequest.method
        if True:

            did = req.params.get('did')
            if (did is None): did = -1
            did = int(did)

            gid = req.params.get('gid')
            if (gid is None): gid = -1
            gid = int(gid)

            pn = req.params.get('pn')
            if (pn==''): pn = 0
            if (pn is None): pn=0
            pn = int(pn)
            if pn<=0: pn = 1

            ps = req.params.get('ps')
            if (ps==''): ps = 0
            if (ps is None): ps = 0
            ps = int(ps)
            if ps <=0: ps = 10

            # print did,gid

            pc = 0

            registry = req.registry

            #－1全部 0未分组 n表示某分组
            csql = """
                    select count(*) as count from eroad_bracelet_patient a
                    left join eroad_bracelet_doctor_patient_rel d on a.id=d.patient_id
                    left join eroad_bracelet_doctor e on e.id=d.doctor_id
                    left join res_partner f on a.partner_id=f.id
                    left join res_partner g on e.partner_id=g.id
                    left join res_country_state h on f.state_id=h.id
                    where d.doctor_id = %s
                      and d.patient_id in (
                        select coalesce(patient_id,0) from patient_group where doctor_id=%s and id=%s
                      )
                """ % (did, did, gid)
            if gid == -1:
                csql = """
                        select count(*) as count from eroad_bracelet_doctor_patient_rel where doctor_id=%s
                    """ % (did)
            if gid == 0:
                csql = """
                        select count(*) as count from eroad_bracelet_patient a
                        left join eroad_bracelet_doctor_patient_rel d on a.id=d.patient_id
                        left join eroad_bracelet_doctor e on e.id=d.doctor_id
                        left join res_partner f on a.partner_id=f.id
                        left join res_partner g on e.partner_id=g.id
                        left join res_country_state h on f.state_id=h.id
                        where d.doctor_id = %s
                          and d.patient_id not in (
                            select coalesce(patient_id,0) from patient_group where doctor_id=%s
                          )
                    """ % (did, did)
            with registry.cursor() as cr:
                cr.execute(csql)
                pc = cr.dictfetchall()[0]["count"]

            # select d.doctor_id,d.patient_id, g.name as dname,f.name as pname,coalesce(h.name,'') as state_name,f.city,a.headimgurl,coalesce(s.eroad_bracelet_patient_id, -1) as isbind,coalesce(j.groups,'') as groups from eroad_bracelet_patient a
            # left join eroad_bracelet_doctor_patient_rel d on a.id=d.patient_id
            # left join eroad_bracelet_doctor e on e.id=d.doctor_id
            # left join res_partner f on a.partner_id=f.id
            # left join res_partner g on e.partner_id=g.id
            # left join res_country_state h on f.state_id=h.id
            # left join (select eroad_bracelet_patient_id from eroad_bracelet_users group by eroad_bracelet_patient_id)
            # s on a.id=s.eroad_bracelet_patient_id
            # left join patient_groups j on j.patient_id=a.id
            # where d.doctor_id = %s
            #   and d.patient_id in (
            #     select coalesce(patient_id,0) from patient_group where doctor_id=%s and id=%s
            #   )
            # order by d.patient_id
            sql = """
                    select a.doctor_id,a.patient_id,a.name as dname,coalesce(f.name,'') as pname,'' as state_name,'' as city,b.headimgurl,
                    coalesce(s.eroad_bracelet_patient_id, -1) as isbind,coalesce(j.groups,'') as groups
                    from patient_group a
                    left join eroad_bracelet_patient b on b.id=a.patient_id
                    left join res_partner f on b.partner_id=f.id
                    left join (select distinct eroad_bracelet_patient_id from eroad_bracelet_users where active=true)
                                        s on b.id=s.eroad_bracelet_patient_id
                    left join patient_groups j on j.patient_id=a.patient_id and j.doctor_id=a.doctor_id
                    where a.doctor_id=%s and a.id=%s
                    order by a.patient_id limit %s OFFSET %s
                    """ % (did,gid,ps,(pn-1)*ps)
            if gid==-1:
                sql = """
                        select d.doctor_id,d.patient_id, g.name as dname,coalesce(f.name,'') as pname,coalesce(h.name,'') as state_name,f.city,a.headimgurl,coalesce(s.eroad_bracelet_patient_id, -1) as isbind,coalesce(j.groups,'') as groups from eroad_bracelet_patient a
                        left join eroad_bracelet_doctor_patient_rel d on a.id=d.patient_id
                        left join eroad_bracelet_doctor e on e.id=d.doctor_id
                        left join res_partner f on a.partner_id=f.id
                        left join res_partner g on e.partner_id=g.id
                        left join res_country_state h on f.state_id=h.id
                        left join (select distinct eroad_bracelet_patient_id from eroad_bracelet_users where active=true)
                        s on a.id=s.eroad_bracelet_patient_id
                        left join patient_groups j on j.patient_id=a.id and j.doctor_id=%s
                        where d.doctor_id=%s
                        order by d.patient_id limit %s OFFSET %s
                      """ % (did, did,ps,(pn-1)*ps)
            if gid==0:
                sql = """
                        select d.doctor_id,d.patient_id, g.name as dname,coalesce(f.name,'') as pname,coalesce(h.name,'') as state_name,f.city,a.headimgurl,coalesce(s.eroad_bracelet_patient_id, -1) as isbind,coalesce(j.groups,'') as groups from eroad_bracelet_patient a
                        left join eroad_bracelet_doctor_patient_rel d on a.id=d.patient_id
                        left join eroad_bracelet_doctor e on e.id=d.doctor_id
                        left join res_partner f on a.partner_id=f.id
                        left join res_partner g on e.partner_id=g.id
                        left join res_country_state h on f.state_id=h.id
                        left join (select distinct eroad_bracelet_patient_id from eroad_bracelet_users where active=true)
                        s on a.id=s.eroad_bracelet_patient_id
                        left join patient_groups j on j.patient_id=a.id and j.doctor_id=%s
                        where d.doctor_id = %s
                          and d.patient_id not in (
                            select coalesce(patient_id,0) from patient_group where doctor_id=%s
                          )
                        order by d.patient_id limit %s OFFSET %s
                        """ % (did,did,did,ps,(pn-1)*ps)
            with registry.cursor() as cr:
                cr.execute(sql)
                doc_patient_agroups_list = cr.dictfetchall()

            templist = []
            group_name = '未分组'
            for group in doc_patient_agroups_list:
                temp = {
                    'did':group['doctor_id'],
                    'pid':group['patient_id'],
                    'dname':group['dname'],
                    'pname':group['pname'],
                    'state':group['state_name'],
                    'city':group['city'],
                    'groups':group['groups'],
                    "headimgurl":group['headimgurl'],
                    "isbind":group['isbind'],
                    "unread":self.doctor_get_unread(req, group['doctor_id'], group['patient_id'])
                }
                group_name = group['groups']
                templist.append(temp)
            #sorted(templist,key=lambda s: s['unread'],reverse=True)
            templist = sorted(templist ,key = lambda x:(x['unread'],x['pid']),reverse=True)
            #templist.sort( 'unread',reverse=Ture)
            success = True

            html = {
                    "success":success,
                    "title": "患者分组列表",
                    "header":"患者分组列表",
                    "group_name":group_name,
                    "pc":pc,
                    "data":templist
                    }

            html = simplejson.dumps(html)

            return request.make_response(html,{
                    'Cache-Control': 'no-cache',
                    'Content-Type': 'text/html; charset=utf-8',
                    'Access-Control-Allow-Origin': '*',
                    'Origin': '*',
                    'Access-Control-Allow-Methods': 'GET,POST',
                    'Access-Control-Allow-Headers': 'Referer, Accept, Origin, User-Agent'
                        })
            # return html
        else:
            return "{%s}" % (method)

    #4 将医生的某患者的某个分组删除
    #(全部)   http://localhost:48269/doctor/patient/delete/group?did=31&gid=1&pid=1542
    @http.route('/doctor/patient/delete/group/', type='http', auth="user", cors='*')
    def doctor_patient_delete_group(self, req, **kw):
        method = req.httprequest.method
        if True:

            did = req.params.get('did')
            if (did is None): did = -1
            did = int(did)

            pid = req.params.get('pid')
            if (pid is None): pid = -1
            pid = int(pid)

            gid = req.params.get('gid')
            if (gid is None): gid = -1
            gid = int(gid)

            registry = req.registry

            sql = """
                    delete from patientgroup_rel where id=%s and patient_id=%s
                    """ % (gid,pid)

            with registry.cursor() as cr:
                cr.execute(sql)
                cr.commit()

            success = True

            html = {
                    "success":success,
                    "title": "删除患者的分组",
                    "header":"删除患者的分组"
                    }

            html = simplejson.dumps(html)

            return request.make_response(html,{
                    'Cache-Control': 'no-cache',
                    'Content-Type': 'text/html; charset=utf-8',
                    'Access-Control-Allow-Origin': '*',
                    'Origin': '*',
                    'Access-Control-Allow-Methods': 'GET,POST',
                    'Access-Control-Allow-Headers': 'Referer, Accept, Origin, User-Agent'
                        })
        else:
            return "{%s}" % (method)

    #5 删除某个分组 意思就是这个分组的患者全部删除
    #(全部)   http://localhost:48269/doctor/patient/delete/agroups?gid=1
    @http.route('/doctor/patient/delete/agroups/', type='http', auth="user", cors='*')
    def doctor_patient_delete_agroups(self, req, **kw):
        method = req.httprequest.method
        if True:
            gid = req.params.get('gid')
            if (gid is None): gid = -1
            gid = int(gid)

            registry = req.registry

            sql = """
                    delete from patientgroup_rel where id=%s
                    """ % (gid)

            with registry.cursor() as cr:
                cr.execute(sql)
                cr.commit()

            sql = """
                    delete from patientgroup where id=%s
                    """ % (gid)

            with registry.cursor() as cr:
                cr.execute(sql)
                cr.commit()

            success = True

            html = {
                    "success":success,
                    "title": "删除患者的分组",
                    "header":"删除患者的分组"
                    }

            html = simplejson.dumps(html)

            return request.make_response(html,{
                    'Cache-Control': 'no-cache',
                    'Content-Type': 'text/html; charset=utf-8',
                    'Access-Control-Allow-Origin': '*',
                    'Origin': '*',
                    'Access-Control-Allow-Methods': 'GET,POST',
                    'Access-Control-Allow-Headers': 'Referer, Accept, Origin, User-Agent'
                        })
            # return html
        else:
            return "{%s}" % (method)

    #6 将所选患者添加到某个分组
    #(全部)   http://localhost:48269/doctor/patient/add/agroups
    @http.route('/doctor/patient/agroups/add', type='json', auth="user",cors="*")
    def doctor_patient_agroups_add(self, req, **kw):
        method = req.httprequest.method
        if True:
            json_req = simplejson.loads(req.httprequest.data)
            print "1",json_req
            did = json_req['did']
            gid = json_req.get('gid')
            gname = json_req.get('gname')
            print "2", gname

            if not gid and not gname:
                success = 'false'
                html = '{"success":"%s"}' % (success)
                return html

            patient_ids = list(json_req.get('pid',[]))
            patient_ids = [int(patient_id) for patient_id in patient_ids]

            registry = req.registry
            patientgroup_obj = registry['patientgroup']
            ids = patientgroup_obj.search(req.cr, SUPERUSER_ID, [('name','=',gname),('doctorid','=',did)])
            if len(ids)>0:
                ret = ids[0]
            else:
                if (gid):
                    ret = gid
                else:
                    vals = {
                        'name':gname,
                        'doctorid':did
                    }
                    ret = patientgroup_obj.create(req.cr, SUPERUSER_ID, vals)
                    req.cr.commit()

            for patient_id in patient_ids:
                sql = """
                        insert into patientgroup_rel(id,patient_id) values(%s,%s)
                        """ % (ret, patient_id)
                with registry.cursor() as cr:
                    cr.execute(sql)
            req.cr.commit()

            success = 'true'

            html = '{"success":"%s"}' % (success)
            return html
        else:
            return "{%s}" % (method)

    #7 某医生的除了某个分组以外的患者列表
    #(某分组) http://localhost:48269/isleep/doctor/patient/unagroups/list?did=31&gid=1
    @http.route('/isleep/doctor/patient/unagroups/list', type='http', auth="user", cors="*")
    def doctor_patient_unagroups_list(self, req, **kw):
        method = req.httprequest.method
        if True:

            did = req.params.get('did')
            if (did is None): did = -1
            did = int(did)

            gid = req.params.get('gid')
            if (gid is None): gid = -1
            gid = int(gid)

            pc = 0

            registry = req.registry

            #－1全部 0未分组 n表示某分组
            csql = """
                    select count(*) as count from eroad_bracelet_patient a
                    left join eroad_bracelet_doctor_patient_rel d on a.id=d.patient_id
                    left join eroad_bracelet_doctor e on e.id=d.doctor_id
                    left join res_partner f on a.partner_id=f.id
                    left join res_partner g on e.partner_id=g.id
                    left join res_country_state h on f.state_id=h.id
                    where d.doctor_id = %s
                      and d.patient_id not in (
                        select coalesce(patient_id,0) from patient_group where doctor_id=%s and id=%s
                      )

                """ % (did, did, gid)

            with registry.cursor() as cr:
                cr.execute(csql)
                pc = cr.dictfetchall()[0]["count"]

            sql = """
                    select d.doctor_id,d.patient_id, g.name as dname,f.name as pname,coalesce(h.name,'') as state_name,f.city,a.headimgurl,coalesce(s.eroad_bracelet_patient_id, -1) as isbind,coalesce(j.groups,'') as groups from eroad_bracelet_patient a
                    left join eroad_bracelet_doctor_patient_rel d on a.id=d.patient_id
                    left join eroad_bracelet_doctor e on e.id=d.doctor_id
                    left join res_partner f on a.partner_id=f.id
                    left join res_partner g on e.partner_id=g.id
                    left join res_country_state h on f.state_id=h.id
                    left join (select distinct eroad_bracelet_patient_id from eroad_bracelet_users where active=true)
                    s on a.id=s.eroad_bracelet_patient_id
                    left join patient_groups j on j.patient_id=a.id and j.doctor_id=%s
                    where d.doctor_id = %s
                      and d.patient_id not in (
                        select coalesce(patient_id,0) from patient_group where doctor_id=%s and id=%s
                      )
                    order by d.patient_id
                    """ % (did,did,did,gid)

            with registry.cursor() as cr:
                cr.execute(sql)
                doc_patient_agroups_list = cr.dictfetchall()

            templist = []
            for group in doc_patient_agroups_list:
                temp = {
                    'did':group['doctor_id'],
                    'pid':group['patient_id'],
                    'dname':group['dname'],
                    'pname':group['pname'],
                    'state':group['state_name'],
                    'city':group['city'],
                    'groups':group['groups'],
                    "headimgurl":group['headimgurl'],
                    "isbind":group['isbind'],
                    "unread":self.doctor_get_unread(req, group['doctor_id'], group['patient_id'])
                }
                templist.append(temp)

            success = True

            html = {
                    "success":success,
                    "title": "患者分组列表",
                    "header":"患者分组列表",
                    "pc":pc,
                    "data":templist
                    }
            # return html
            html = simplejson.dumps(html)

            return request.make_response(html,{
                    'Cache-Control': 'no-cache',
                    'Content-Type': 'text/html; charset=utf-8',
                    'Access-Control-Allow-Origin': '*',
                    'Origin': '*',
                    'Access-Control-Allow-Methods': 'GET,POST',
                    'Access-Control-Allow-Headers': 'Referer, Accept, Origin, User-Agent'
                        })
        else:
            return "{%s}" % (method)

    #8 将所选患者的某个分组进行更新
    #(全部)   http://localhost:48269/isleep/doctor/patient/agroups/update?did=31&gid=2&
    @http.route('/isleep/doctor/patient/agroups/update', type='json', auth="user", cors='*')
    def doctor_patient_agroups_update(self, req, **kw):
        method = req.httprequest.method
        if True:
            json_req = simplejson.loads(req.httprequest.data)
            did = json_req['did']
            gid = json_req['gid']
            gname = json_req['gname']

            if not gid and not gname:
                success = 'false'
                html = '{"success":"%s"}' % (success)
                return html



            patient_ids = list(json_req.get('pid',[]))
            patient_ids = [int(patient_id) for patient_id in patient_ids]

            registry = req.registry
            patientgroup_obj = registry['patientgroup']

            #先判断
            # print gname, did
            ids = patientgroup_obj.search(req.cr, SUPERUSER_ID, [('name','=',gname),('doctorid','=',did)])
            if len(ids)>0 and int(ids[0])!=int(gid):#表示医生的标签存在，则合并患者
                # print "表示医生的标签存在，则合并患者",ids[0],gid
                for patient_id in patient_ids:
                    sql = """
                            select * from patientgroup_rel where id=%s and patient_id=%s
                        """ % (ids[0], patient_id)
                    with registry.cursor() as cr:
                        cr.execute(sql)
                        patientgroup_rel_lists = cr.dictfetchall()
                    if patientgroup_rel_lists.__len__()<=0:
                        try:
                            sql = """
                                    insert into patientgroup_rel(id,patient_id) values(%s,%s)
                                    """ % (ids[0], patient_id)
                            with registry.cursor() as cr:
                                cr.execute(sql)
                        except Exception,e:
                            pass
                    sql = """
                            delete from patientgroup_rel where id=%s
                            """ % (gid)
                    with registry.cursor() as cr:
                        cr.execute(sql)
                    sql = """
                            delete from patientgroup where id=%s and doctorid=%s
                            """ % (gid, did)
                    with registry.cursor() as cr:
                        cr.execute(sql)
                req.cr.commit()
            else:
                pass
                #更新分组名称
                vals = {
                    'name':gname
                }
                ret = patientgroup_obj.write(req.cr, SUPERUSER_ID, int(gid), vals)
                req.cr.commit()

                sql = """
                        delete from patientgroup_rel where id=%s
                        """ % (gid)
                with registry.cursor() as cr:
                    cr.execute(sql)

                for patient_id in patient_ids:
                    sql = """
                            insert into patientgroup_rel(id,patient_id) values(%s,%s)
                            """ % (gid, patient_id)
                    with registry.cursor() as cr:
                        cr.execute(sql)
                req.cr.commit()

            success = 'true'

            html = '{"success":"%s"}' % (success)
            return html
        else:
            return "{%s}" % (method)


    #9 将所选患者的某个分组进行更新
    #(全部)   http://localhost:48269/doctor/patient/agroups/update/bak?did=31&gid=2&
    @http.route('/doctor/patient/agroups/update/bak', type='json', auth="user", cors='*')
    def doctor_patient_agroups_update_bak(self, req, **kw):
        method = req.httprequest.method
        if True:
            json_req = simplejson.loads(req.httprequest.data)
            did = json_req['did']
            gid = json_req['gid']
            gname = json_req['gname']

            if not gid and not gname:
                success = 'false'
                html = '{"success":"%s"}' % (success)
                return html



            patient_ids = list(json_req.get('pid',[]))
            patient_ids = [int(patient_id) for patient_id in patient_ids]

            registry = req.registry
            patientgroup_obj = registry['patientgroup']

            #先判断
            ids = patientgroup_obj.search(req.cr, SUPERUSER_ID, [('name','=',gname),('doctorid','=',did)])

            #更新分组名称
            vals = {
                'name':gname
            }
            ret = patientgroup_obj.write(req.cr, SUPERUSER_ID, int(gid), vals)
            req.cr.commit()

            sql = """
                    delete from patientgroup_rel where id=%s
                    """ % (gid)
            with registry.cursor() as cr:
                cr.execute(sql)

            for patient_id in patient_ids:
                sql = """
                        insert into patientgroup_rel(id,patient_id) values(%s,%s)
                        """ % (gid, patient_id)
                with registry.cursor() as cr:
                    cr.execute(sql)
            req.cr.commit()

            success = 'true'

            html = '{"success":"%s"}' % (success)
            return html
        else:
            return "{%s}" % (method)


    @http.route('/isleep/doctor/patient/search/name', type='json', auth="none")
    def doctor_patient_search_name(self, req, **kw):
        '''
        说明:医生搜索患者功能接口
        url:/isleep/doctor/patient/search/name
        @param req:
            {
                "doctor_id":4568,
                "keys":"张"
            }
        @param kw:
        @return:
            {
                "success":True,
                "message":"请求成功",
                "title":"医生搜索患者",
                data = [
                            {
                                'did':'doctor_id',
                                'pid':'patient_id',
                                'dname':'dname',
                                'pname':'pname',
                                'state':'state_name',
                                'city':'city',
                                'groups':'groups',
                                "headimgurl":'headimgurl',
                                "isbind":'isbind',
                                "unread":self.doctor_get_unread(req, group['doctor_id'], group['patient_id'])
                            },
                            .......
                        ]
            }
        '''
        method = req.httprequest.method
        if method =="POST" or method=="GET":
            doctor_id = int(req.jsonrequest.get('doctor_id',-1))
            keys = req.jsonrequest.get('keys','')
            if doctor_id>0 and keys:
                doctor_obj = req.registry['eroad.bracelet.doctor']
                patient_obj = req.registry['eroad.bracelet.patient']
                city_obj = req.registry['res.city']
                bracelet_obj = req.registry['eroad.bracelet.users']
                #domain_patient = [('id','=',doctor_id)]
                pinyin = HanYuPinYin()
                doctors = doctor_obj.read(req.cr, SUPERUSER_ID, doctor_id, fields=['patients','name'])
                if doctors:
                    doctor_name = doctors['name']
                    patient_ids = doctors['patients'] if doctors['patients'] else []
                    domain_patient = [('id','in',patient_ids),('name','like',keys),('subscribe','=',1)]
                    patients = patient_obj.browse(req.cr, SUPERUSER_ID, patient_obj.search(req.cr, SUPERUSER_ID,domain_patient))
                    data =[]
                    for patient in patients:
                        message = {}
                        message['did'] = doctor_id
                        #message['dname'] = doctor_name
                        message['pid'] = patient.id
                        message['pname'] = patient.name
                        message['headimgurl'] = patient.headimgurl if patient.headimgurl else ''
                        if message['headimgurl']=='':
                            if patient.sex ==1:  #男
                                message['headimgurl'] ='/eroad_bracelet/static/src/img/default_man.png'
                            elif patient.sex ==2:   #女
                                message['headimgurl'] ='/eroad_bracelet/static/src/img/default_woman.png'
                            else:  #未知
                                message['headimgurl'] ='/eroad_bracelet/static/src/img/default_nosex.png'

                        #message['groups'] = patient['groups'][0] if patient['groups'] else ''
                        message['groups'] = ''
                        groups_name = ""
                        if patient.groups and len(patient.groups)>0:
                            group_name_list = [{"name":groups.name} for groups in patient.groups if groups.name and groups.doctorid and groups.doctorid.id==doctor_id ]
                            group_name_list = sorted(group_name_list, key=operator.itemgetter('name'), reverse=False)
                            for i in xrange(len(group_name_list)):
                                name_pinyin = pinyin.hanzi2pinyin(group_name_list[i]['name'])
                                group_name_list[i]['name_pinyin'] = name_pinyin
                            group_name_list = sorted(group_name_list, key=operator.itemgetter('name_pinyin'), reverse=False)
                            for names in group_name_list:
                                if groups_name!='':
                                    groups_name = groups_name + "  "
                                groups_name = groups_name + names['name']

                        message['groups'] = groups_name if groups_name!='' else '未分组'

                        message['unread'] = self.doctor_get_unread(req, doctor_id, message['pid'])
                        is_bracelet = bracelet_obj.search(req.cr, SUPERUSER_ID,[('eroad_bracelet_patient_id','=',message['pid'])])
                        if is_bracelet:
                            message['isbind'] = is_bracelet[0]
                        else:
                            message['isbind'] = -1
                        data.append(message)
                    data = sorted(data, key=operator.itemgetter('unread'), reverse=False)
                    success = True
                    message = '请求成功'
                else:
                    success = False
                    message = '请输入正确的关键字和医生id'
                    data = []
            else:
                success = False
                message = '请输入正确的关键字和医生id'
                data = []
        else:
            success = False
            message = '非get或post请求'
            data = []

        html = {
            'success':success,
            'message':message,
            'title':'关键词查询患者',
            'data':data
        }
        return html


    #获取医生的患者分类列表
    @http.route('/isleep/doctor/patient/groups/list_new', type='json', auth="none")
    def doctor_patient_group_list_new(self, req, **kw):
        '''
        说明:医生查看患者列表时分组列表
        @param req:
            {"did":56567}
        @param kw:
        @return:
            {
                "success":success,
                "title": "患者分组",
                "header":"患者分组",
                "pc":pc,
                "data":[
                        {'gid':group['id'],
                        'name':group['name'],
                        'did':did,
                        'pc':group['pc']},...
                    ]
            }
        '''
        method = req.httprequest.method
        if method=="POST" or method=="GET":
            doctor_id = int(req.jsonrequest.get('did',-1))
            if doctor_id>0:
                patientgroup_obj = req.registry['patientgroup']
                patient_obj = req.registry['eroad.bracelet.patient']
                doctor_obj = req.registry['eroad.bracelet.doctor']
                domain_p = [('id','=',doctor_id),('patients.subscribe','=',1)]
                patient_count = doctor_obj.browse(req.cr, SUPERUSER_ID, doctor_obj.search(req.cr, SUPERUSER_ID, domain_p))
                active_patient_id = [active.id for active in patient_count.patients if active.subscribe and active.subscribe ==1]
                pc = len(active_patient_id)
                # pc = len(patient_count[0]['patients']) if patient_count[0]['patients'] else 0
                domain_doctor = [('doctorid','=',doctor_id)]
                group_names = patientgroup_obj.browse(req.cr, SUPERUSER_ID,patientgroup_obj.search(req.cr,SUPERUSER_ID,domain_doctor))
                group_list= []
                pinyin = HanYuPinYin()
                pc_group = 0
                patient_ids =[]
                for group_name in group_names:
                    group_dict = {}
                    group_dict['gid'] = group_name.id
                    group_dict['name'] = group_name.name if group_name.name else ''
                    name_pinyin = pinyin.hanzi2pinyin(group_dict['name'])
                    group_dict['name_pinyin'] = name_pinyin
                    patient_id = [gruops.id for gruops in group_name.patient_id if gruops and gruops.subscribe and gruops.subscribe==1]
                    group_dict['pc'] = len(patient_id)
                    if group_dict['pc'] !=0:
                        patient_ids = list(set(patient_ids)| set(group_name['patient_id']))
                    group_list.append(group_dict)
                pc_left = pc - len(patient_ids)
                group_list = sorted(group_list, key=operator.itemgetter('name'), reverse=False)
                group_list2 = sorted(group_list, key=operator.itemgetter('name_pinyin'), reverse=False)
                # group_list2 = group_list.sort(lambda x,y : cmp(x['name'], y['name']))
                if group_list2:
                    left_patient = {}
                    left_patient['gid'] = 0
                    left_patient['name'] = '未分组'
                    left_patient['pc'] = pc_left
                    group_list2.insert(0,left_patient)


                all_patient = {}
                all_patient['gid'] = -1
                all_patient['name'] = '全部'

                all_patient['pc'] = pc
                group_list2.insert(0,all_patient)

                success = True
                header = '请求成功'
            else:
                header = '医生id不正确'
                group_list2 =[]
                success = False
                pc = 0
        else:
            header = '非POST或GET请求'
            group_list2 =[]
            success = False
            pc = 0

        html = {
            'success':success,
            "title": "患者分组",
            "header":header,
            "pc":pc,
            "data":group_list2
        }
        return html


    #3某医生的某个分组的患者列表
    #(全部)   http://localhost:48269/isleep/doctor/patient/agroups/list?did=31&gid=-1
    #(未分组) http://localhost:48269/isleep/doctor/patient/agroups/list?did=31&gid=0
    #(某分组) http://localhost:48269/isleep/doctor/patient/agroups/list?did=31&gid=5
    @http.route('/isleep/doctor/patient/agroups/list_new', type='json', auth="none")
    def doctor_patient_agroups_list_new(self, req, **kw):
        '''
        说明:获取医生的患者列表,gid=-1,获取全部,gid=0,获取未分组的,gid=3,获取ID为3的分组的用户列表
        url:isleep/doctor/patient/agroups/list_new
        @param req:
        {
            "did":56567,
            "gid":-1
        }
        @param kw:
        @return:
        {
            "success":success,
            "title": "患者分组列表",
            "header":"患者分组列表",
            "group_name":group_name,
            "pc":pc,
            "data":[
                {
                    'did':'doctor_id',
                    'pid':'patient_id',
                    'dname':'dname',
                    'pname':'pname',
                    'groups':'groups',
                    "headimgurl":'headimgurl',
                    "isbind":'isbind',
                    "unread":self.doctor_get_unread(req, group['doctor_id'], group['patient_id'])
                },...
            ]
        }
        '''
        method = req.httprequest.method
        if method=="POST" or method=="GET":
            doctor_id = int(req.jsonrequest.get('did',-1))
            gid = int(req.jsonrequest.get('gid',-1))
            #－1全部 0未分组 n表示某分组
            pn = req.jsonrequest.get('pn',1)
            ps = req.jsonrequest.get('ps',10)
            pinyin = HanYuPinYin()
            if doctor_id>0:

                patientgroup_obj = req.registry['patientgroup']
                patient_obj = req.registry['eroad.bracelet.patient']
                doctor_obj = req.registry['eroad.bracelet.doctor']
                bracelet_obj = req.registry['eroad.bracelet.users']
                if gid ==-1:
                    group_name ="全部"
                    doctors= doctor_obj.browse(req.cr, SUPERUSER_ID,doctor_id)
                    patient_message = []

                    if doctors.patients:
                        for patient in doctors.patients:
                            if patient.subscribe and patient.subscribe==1:
                                message = {}
                                message['did'] = doctor_id
                                message['pid'] = patient.id if patient.id else ''
                                message['pname'] = patient.name if patient.name else ''
                                message['headimgurl'] = patient.headimgurl if patient.headimgurl else ''
                                if message['headimgurl']=='':
                                    if patient.sex ==1:  #男
                                        message['headimgurl'] ='/eroad_bracelet/static/src/img/default_man.png'
                                    elif patient.sex ==2:   #女
                                        message['headimgurl'] ='/eroad_bracelet/static/src/img/default_woman.png'
                                    else:  #未知
                                        message['headimgurl'] ='/eroad_bracelet/static/src/img/default_nosex.png'
                                message['groups'] = ''
                                groups_name = ""
                                if patient.groups and len(patient.groups)>0:
                                    group_name_list = [{"name":groups.name} for groups in patient.groups if groups.name and groups.doctorid and groups.doctorid.id==doctor_id ]
                                    group_name_list = sorted(group_name_list, key=operator.itemgetter('name'), reverse=False)
                                    for i in xrange(len(group_name_list)):
                                        name_pinyin = pinyin.hanzi2pinyin(group_name_list[i]['name'])
                                        group_name_list[i]['name_pinyin'] = name_pinyin
                                    group_name_list = sorted(group_name_list, key=operator.itemgetter('name_pinyin'), reverse=False)
                                    for names in group_name_list:
                                        if groups_name!='':
                                            groups_name = groups_name + "  "
                                        groups_name = groups_name + names['name']

                                message['groups'] = groups_name if groups_name!='' else '未分组'
                                message['unread'] = self.doctor_get_unread(req, doctor_id, message['pid'])
                                is_bracelet = bracelet_obj.search(req.cr, SUPERUSER_ID,[('eroad_bracelet_patient_id','=',message['pid'])])
                                if is_bracelet:
                                    message['isbind'] = is_bracelet[0]
                                else:
                                    message['isbind'] = -1
                                patient_message.append(message)
                    patient_message = sorted(patient_message, key=operator.itemgetter('unread'), reverse=False)
                    pc = len(patient_message)
                    success = True
                elif gid==0:
                    group_name ="未分组"
                    doctors= doctor_obj.browse(req.cr, SUPERUSER_ID,doctor_id)
                    patient_message = []
                    if doctors.patients:
                        for patient in doctors.patients:
                            if  patient.subscribe and patient.subscribe==1:
                                if patient.groups.ids==[] or [group_id.doctorid.id for group_id in patient.groups  if group_id.doctorid.id==doctor_id]==[]:
                                    message = {}
                                    message['did'] = doctor_id
                                    message['pid'] = patient.id if patient.id else ''
                                    message['pname'] = patient.name if patient.name else ''
                                    message['headimgurl'] = patient.headimgurl if patient.headimgurl else ''
                                    if message['headimgurl']=='':
                                        if patient.sex ==1:  #男
                                            message['headimgurl'] ='/eroad_bracelet/static/src/img/default_man.png'
                                        elif patient.sex ==2:   #女
                                            message['headimgurl'] ='/eroad_bracelet/static/src/img/default_woman.png'
                                        else:  #未知
                                            message['headimgurl'] ='/eroad_bracelet/static/src/img/default_nosex.png'
                                    message['groups'] = '未分组'
                                    # groups_name = ""
                                    # if patient.groups and len(patient.groups)>0:
                                    #     for groups in patient.groups:
                                    #         if groups_name!='':
                                    #             groups_name = groups_name + "  "
                                    #         groups_name += groups.name if groups.name else ''
                                    #     message['groups'] = groups_name
                                    message['unread'] = self.doctor_get_unread(req, doctor_id, message['pid'])
                                    is_bracelet = bracelet_obj.search(req.cr, SUPERUSER_ID,[('eroad_bracelet_patient_id','=',message['pid'])])
                                    if is_bracelet:
                                        message['isbind'] = is_bracelet[0]
                                    else:
                                        message['isbind'] = -1
                                    patient_message.append(message)
                    patient_message = sorted(patient_message, key=operator.itemgetter('unread'), reverse=False)
                    pc = len(patient_message)
                    success = True
                else:
                    groups = patientgroup_obj.browse(req.cr, SUPERUSER_ID, gid)
                    group_name = groups.name
                    patients = groups.patient_id
                    patient_message = []
                    for patient in patients:
                        if patient.subscribe and patient.subscribe==1:
                            message = {}
                            message['did'] = doctor_id
                            message['pid'] = patient.id if patient.id else ''
                            message['pname'] = patient.name if patient.name else ''

                            message['headimgurl'] = patient.headimgurl if patient.headimgurl else ''
                            if message['headimgurl']=='':
                                if patient.sex ==1:  #男
                                    message['headimgurl'] ='/eroad_bracelet/static/src/img/default_man.png'
                                elif patient.sex ==2:   #女
                                    message['headimgurl'] ='/eroad_bracelet/static/src/img/default_woman.png'
                                else:  #未知
                                    message['headimgurl'] ='/eroad_bracelet/static/src/img/default_nosex.png'
                            message['groups'] = ''
                            groups_name = ""
                            if patient.groups and len(patient.groups)>0:
                                    group_name_list = [{"name":groups.name} for groups in patient.groups if groups.name and groups.doctorid and groups.doctorid.id==doctor_id ]
                                    group_name_list = sorted(group_name_list, key=operator.itemgetter('name'), reverse=False)
                                    for i in xrange(len(group_name_list)):
                                        name_pinyin = pinyin.hanzi2pinyin(group_name_list[i]['name'])
                                        group_name_list[i]['name_pinyin'] = name_pinyin
                                    group_name_list = sorted(group_name_list, key=operator.itemgetter('name_pinyin'), reverse=False)
                                    for names in group_name_list:
                                        if groups_name!='':
                                            groups_name = groups_name + "  "
                                        groups_name = groups_name + names['name']

                                    message['groups'] = groups_name
                            message['unread'] = self.doctor_get_unread(req, doctor_id, message['pid'])
                            is_bracelet = bracelet_obj.search(req.cr, SUPERUSER_ID,[('eroad_bracelet_patient_id','=',message['pid'])])
                            if is_bracelet:
                                message['isbind'] = is_bracelet[0]
                            else:
                                message['isbind'] = -1
                            patient_message.append(message)
                    patient_message = sorted(patient_message, key=operator.itemgetter('unread'), reverse=False)
                    pc = len(patient_message)
                    success = True
            else:
                pc = 0
                success = False
                patient_message = []
                group_name = ''
        else:
            pc = 0
            success = False
            patient_message = []
            group_name = ''

        html = {
                "success":success,
                "title": "患者分组列表",
                "header":"患者分组列表",
                "group_name":group_name,
                "pc":pc,
                "data":patient_message
                }
        return html

    #7 某医生的除了某个分组以外的患者列表
    #(某分组) http://localhost:48269/isleep/doctor/patient/unagroups/list_new?did=31&gid=1
    @http.route('/isleep/doctor/patient/unagroups/list_new', type='json', auth="none")
    def doctor_patient_unagroups_list_new(self, req, **kw):
        '''
        说明:进入患者分组添加患者时,列表列出的患者列表,此时只列出该分组以外的患者
        url:/isleep/doctor/patient/unagroups/list_new
        @param req:
            {
                "did":56567,
                "gid":117
            }
        @param kw:
        @return:
            {
                "success":True,
                "title": "患者分组列表",
                "header":"患者分组列表",
                "pc":pc,
                "data":[
                        {
                            'did':group['doctor_id'],
                            'pid':group['patient_id'],
                            'dname':group['dname'],
                            'pname':group['pname'],
                            'groups':group['groups'],
                            "headimgurl":group['headimgurl'],
                            "isbind":group['isbind'],
                            "unread":self.doctor_get_unread(req, group['doctor_id'], group['patient_id'])
                        }
                ]
            }
        '''

        method = req.httprequest.method
        if method=="POST" or method=="GET":
            doctor_id = int(req.jsonrequest.get('did',-1))
            gid = int(req.jsonrequest.get('gid',-1))
            #－1全部 0未分组 n表示某分组
            pn = req.jsonrequest.get('pn',1)
            ps = req.jsonrequest.get('ps',10)
            if doctor_id>0 and gid>0:
                patientgroup_obj = req.registry['patientgroup']
                patient_obj = req.registry['eroad.bracelet.patient']
                doctor_obj = req.registry['eroad.bracelet.doctor']
                bracelet_obj = req.registry['eroad.bracelet.users']
                groups = patientgroup_obj.browse(req.cr, SUPERUSER_ID, gid)
                group_name = groups.name
                patients = groups.patient_id
                group_patients_ids = [patient.id for patient in groups.patient_id if patient and patient.subscribe and patient.subscribe==1]
                doctor_patients = doctor_obj.browse(req.cr, SUPERUSER_ID, doctor_id)
                doctor_patients_ids = [patient.id for patient in doctor_patients.patients if patient and patient.subscribe and patient.subscribe==1]
                patients_ids = list(set(doctor_patients_ids)-set(group_patients_ids))
                pinyin = HanYuPinYin()
                patients = patient_obj.browse(req.cr, SUPERUSER_ID,patients_ids)
                patient_message =[]
                for patient in patients:
                    message = {}
                    message['did'] = doctor_id
                    message['pid'] = patient.id if patient.id else ''
                    message['pname'] = patient.name if patient.name else ''
                    message['headimgurl'] = patient.headimgurl if patient.headimgurl else ''
                    if message['headimgurl']=='':
                        if patient.sex ==1:  #男
                            message['headimgurl'] ='/eroad_bracelet/static/src/img/default_man.png'
                        elif patient.sex ==2:   #女
                            message['headimgurl'] ='/eroad_bracelet/static/src/img/default_woman.png'
                        else:  #未知
                            message['headimgurl'] ='/eroad_bracelet/static/src/img/default_nosex.png'
                    message['groups'] = ''
                    groups_name = ""
                    if patient.groups and len(patient.groups)>0:
                        group_name_list = [{"name":groups.name} for groups in patient.groups if groups.name and groups.doctorid and groups.doctorid.id==doctor_id ]
                        group_name_list = sorted(group_name_list, key=operator.itemgetter('name'), reverse=False)
                        for i in xrange(len(group_name_list)):
                            name_pinyin = pinyin.hanzi2pinyin(group_name_list[i]['name'])
                            group_name_list[i]['name_pinyin'] = name_pinyin
                        group_name_list = sorted(group_name_list, key=operator.itemgetter('name_pinyin'), reverse=False)
                        for names in group_name_list:
                            if groups_name!='':
                                groups_name = groups_name + "  "
                            groups_name = groups_name + names['name']

                    message['groups'] = groups_name if groups_name!='' else '未分组'
                    message['unread'] = self.doctor_get_unread(req, doctor_id, message['pid'])
                    is_bracelet = bracelet_obj.search(req.cr, SUPERUSER_ID,[('eroad_bracelet_patient_id','=',message['pid'])])
                    if is_bracelet:
                        message['isbind'] = is_bracelet[0]
                    else:
                        message['isbind'] = -1
                    patient_message.append(message)
                pc = len(patient_message)
                success = True
                header = '成功'


            else:
                success = False
                header ='患者分组或医生id不正确'
                pc=0
                patient_message =[]
        else:
                success = False
                header ='患者分组或医生id不正确'
                pc=0
                patient_message =[]

        html = {
                "success":success,
                "title": "患者分组列表",
                "header":header,
                "pc":pc,
                "data":patient_message
                }
        return html

    #5 删除某个分组 意思就是这个分组的患者全部删除
    #(全部)   http://localhost:48269/isleep/doctor/patient/delete/agroups_new?gid=1
    @http.route('/isleep/doctor/patient/delete/agroups_new', type='json', auth="none")
    def doctor_patient_delete_agroups_new(self, req, **kw):
        '''
            说明:删除分组,该分组下患者也删除
            url:/isleep/doctor/patient/delete/agroups_new
        @param req:
            {
                "did":56567,
                "gid":118
            }
        @param kw:
        @return:
            {
                "success":success,
                "title": "删除患者的分组",
                "header":"删除患者的分组"
                }
        '''
        method = req.httprequest.method
        if method=="POST" or method=="GET":
            doctor_id = int(req.jsonrequest.get('did',-1))
            gid = int(req.jsonrequest.get('gid',-1))
            #－1全部 0未分组 n表示某分组
            if doctor_id>0 and gid>0:
                patientgroup_obj = req.registry['patientgroup']
                vals = {
                    #"doctorid":-1,
                    "patient_id":[(5,0,0)]
                }
                group_update = patientgroup_obj.write(req.cr ,SUPERUSER_ID,gid, vals)
                group_delete = patientgroup_obj.unlink(req.cr, SUPERUSER_ID,gid)
                success = True
                header = '删除成功'
            else:
                success = False
                header = '医生ID或组id不正确'
        else:
            success = False
            header = '非post或get请求'

        html = {
                "success":success,
                "title": "删除患者的分组",
                "header":header
                }
        return html


    #6 将所选患者添加到某个分组
    #(全部)   http://localhost:48269/isleep/doctor/patient/agroups/add_new
    @http.route('/isleep/doctor/patient/agroups/add_new', type='json', auth="none")
    def doctor_patient_agroups_add_new(self, req, **kw):
        '''
        说明:将所选患者新建分组
        url:/isleep/doctor/patient/agroups/add_new
        @param req:
            {
                'did':56567,
                'pid':[1597,1595],
                'gname':'二分组'
            }
        @param kw:
        @return:
        {
            'success':True,
            'title':'新建分组',
            'message':'成功',
            'is_name_exist':False
        }
        '''
        method = req.httprequest.method
        if method=="POST" or method=="GET":
            doctor_id = int(req.jsonrequest.get('did',-1))
            group_name = req.jsonrequest.get('gname','')
            patient_ids = list(req.jsonrequest.get('pid',[]))
            patient_ids = [int(patient_id) for patient_id in patient_ids]
            if doctor_id>0 and group_name:
                patientgroup_obj = req.registry['patientgroup']
                group_name_domin = [('name','=',group_name),('doctorid','=',doctor_id)]
                group_id_exist = patientgroup_obj.search(req.cr, SUPERUSER_ID,group_name_domin)
                if not group_id_exist:
                    vals = {
                        'name':group_name,
                        'doctorid':doctor_id
                    }

                    group_id = patientgroup_obj.create(req.cr, SUPERUSER_ID, vals)
                    if patient_ids:
                        patient_add = patientgroup_obj.write(req.cr, SUPERUSER_ID,group_id,{'patient_id':[(6,0,patient_ids)]})
                    else:
                        patient_add = True
                    if patient_add:
                        success = True
                        message = "成功"
                        is_name_exist = False
                    else:
                        success = False
                        message = "失败"
                        is_name_exist = False
                else:
                    success = False
                    message = "分组名已经存在"
                    is_name_exist = True
            else:
                success = False
                message = "医生ID或者组名错误"
                is_name_exist = False
        else:
            success = False
            message = '非post或get请求'
            is_name_exist = False
        html = {
            'success':success,
            'message':message,
            'title':'医生新建患者分组',
            'is_name_exist':is_name_exist
        }
        return html



    #8 将所选患者的某个分组进行更新,包括更新分组名称和分组内成员
    #(全部)   http://localhost:48269/isleep/doctor/patient/agroups/update_new?did=31&gid=2&
    @http.route('/isleep/doctor/patient/agroups/update_new', type='json', auth="none")
    def doctor_patient_agroups_update_new(self, req, **kw):
        '''
            说明:将所选患者的某个分组进行更新,包括更新分组名称和分组内成员
            url:/isleep/doctor/patient/agroups/update_new
        @param req:
            {
                'did':56567,
                'gid':118,
                'gname':'游记小分队',
                'pid':[1593,1595]
            }
        @param kw:
        @return:
            {
                'success':True,
                'title':'修改患者分组',
                'message':'成功',
                'is_name_exist':False
            }
        '''
        method = req.httprequest.method
        if method=="POST" or method=="GET":
            doctor_id = int(req.jsonrequest.get('did',-1))
            group_name = req.jsonrequest.get('gname','')
            group_id = int(req.jsonrequest.get('gid',-1))
            patient_ids = list(req.jsonrequest.get('pid',[]))
            patient_ids = [int(patient_id) for patient_id in patient_ids]
            if doctor_id>0 and group_id>0:
                patientgroup_obj = req.registry['patientgroup']
                if group_name:
                    domain_name = [('name','=',group_name),('doctorid','=',doctor_id)]
                    name_exist = patientgroup_obj.search(req.cr, SUPERUSER_ID, domain_name)
                    if len(name_exist)>1 or (len(name_exist)==1 and group_id!= name_exist[0]):
                        is_name_exist = True
                        success = False
                        message = '分组号已经存在'
                    else:
                        if patient_ids:
                            vals = {
                                'name':group_name,
                                'patient_id':[(6,0,patient_ids)],
                                #'doctorid':doctor_id
                            }
                        else:
                            vals = {
                                'name':group_name,
                                'patient_id':[(5,0,0)]
                                #'doctorid':doctor_id
                            }
                        group_id = patientgroup_obj.write(req.cr, SUPERUSER_ID,group_id, vals)
                        if group_id:
                            success = True
                            is_name_exist = False
                            message = "成功"
                        else:
                            success = False
                            message = "失败"
                            is_name_exist = False

                else:
                    vals = {
                        'patient_id':[(6,0,patient_ids)],
                    }

                    group_id = patientgroup_obj.write(req.cr, SUPERUSER_ID,group_id, vals)
                    if group_id:
                        success = True
                        message = "成功"
                        is_name_exist = False
                    else:
                        success = False
                        message = "失败"
                        is_name_exist = False
            else:
                success = False
                message = "医生ID或者组id错误"
                is_name_exist = False
        else:
            success = False
            message = '非post或get请求'
            is_name_exist = False
        html = {
            'is_name_exist' : is_name_exist,
            'success':success,
            'message':message,
            'title':'修改患者分组'
        }
        return html

    #(全部)   http://localhost:48269/isleep/doctor/patient/agroups/update_new?did=31&gid=2&
    @http.route('/isleep/doctor/patient/group/modifyfield', type='json', auth="user")
    def doctor_patient_modify_namy2many_new(self, req, **kw):
        '''
        说明:在patientgroup 表中存在doctorid,以前为integer字段,现在要调整为many2one字段,若医生中相应的记录删除,升级模块失败
        @param req:
        @param kw:
        @return:
        '''
        patient_group_obj = req.registry['patientgroup']
        doctor_obj = req.registry['eroad.bracelet.doctor']
        patient_group_ids = patient_group_obj.search_read(req.cr, SUPERUSER_ID, [],fields=['doctorid'])
        for patient_group_id in patient_group_ids:
            if patient_group_id['doctorid']:
                domain_patient = [('id','=',patient_group_id['doctorid'])]
                doctor_id = doctor_obj.search(req.cr, SUPERUSER_ID, domain_patient)
                if not doctor_id:
                    delete_ids = patient_group_obj.unlink(req.cr, SUPERUSER_ID, patient_group_id['id'] )

        json = simplejson({"success":True})
        html = (json,{
            'Cache-Control': 'no-cache',
            'Content-Type': 'text/html; charset=utf-8',
            'Access-Control-Allow-Origin': '*',
            'Origin': '*',
            'Access-Control-Allow-Methods': 'GET,POST',
            'Access-Control-Allow-Headers': 'Referer, Accept, Origin, User-Agent'
        })
        return html


def dedupe(items, key=None):
    seen = set()
    for item in items:
        val = item if key is None else key(item)
        if val not in seen:
            yield item
            seen.add(val)
